/**
 * 文件上传相关API接口
 */

import { request, mockSuccess, mockError } from '@/utils/request'

/**
 * 上传单个文件
 * @param {FormData} formData - 文件数据
 * @param {object} options - 上传选项
 * @returns {Promise} 上传结果
 */
export const uploadFile = (formData, options = {}) => {
  return request.upload('/upload/file', formData, options, () => {
    // 模拟文件信息
    const file = formData.get('file')
    const fileName = file ? file.name : 'unknown.txt'
    const fileSize = file ? file.size : 1024
    const fileExtension = fileName.split('.').pop().toLowerCase()
    
    // 文件类型检查
    const allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt']
    if (!allowedTypes.includes(fileExtension)) {
      return mockError('不支持的文件类型', 400)
    }
    
    // 文件大小检查（10MB）
    if (fileSize > 10 * 1024 * 1024) {
      return mockError('文件大小不能超过10MB', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      filename: `${Date.now()}_${fileName}`,
      originalName: fileName,
      size: fileSize,
      extension: fileExtension,
      mimeType: file ? file.type : 'text/plain',
      url: `/uploads/${Date.now()}_${fileName}`,
      thumbnailUrl: ['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension) ? `/uploads/thumb_${Date.now()}_${fileName}` : null,
      uploadTime: new Date().toISOString(),
      hash: `md5_${Date.now()}`,
      category: getFileCategory(fileExtension)
    }, '文件上传成功')
  })
}

/**
 * 上传多个文件
 * @param {FormData} formData - 文件数据
 * @param {object} options - 上传选项
 * @returns {Promise} 上传结果
 */
export const uploadMultipleFiles = (formData, options = {}) => {
  return request.upload('/upload/multiple', formData, options, () => {
    const files = formData.getAll('files')
    
    if (!files || files.length === 0) {
      return mockError('请选择要上传的文件', 400)
    }
    
    if (files.length > 10) {
      return mockError('一次最多上传10个文件', 400)
    }
    
    const uploadedFiles = files.map((file, index) => {
      const fileName = file.name
      const fileSize = file.size
      const fileExtension = fileName.split('.').pop().toLowerCase()
      
      return {
        id: Date.now() + index,
        filename: `${Date.now() + index}_${fileName}`,
        originalName: fileName,
        size: fileSize,
        extension: fileExtension,
        mimeType: file.type,
        url: `/uploads/${Date.now() + index}_${fileName}`,
        thumbnailUrl: ['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension) ? `/uploads/thumb_${Date.now() + index}_${fileName}` : null,
        uploadTime: new Date().toISOString(),
        hash: `md5_${Date.now() + index}`,
        category: getFileCategory(fileExtension)
      }
    })
    
    return mockSuccess({
      files: uploadedFiles,
      successCount: uploadedFiles.length,
      failCount: 0
    }, `成功上传${uploadedFiles.length}个文件`)
  })
}

/**
 * 上传图片
 * @param {FormData} formData - 图片数据
 * @param {object} options - 上传选项
 * @returns {Promise} 上传结果
 */
export const uploadImage = (formData, options = {}) => {
  return request.upload('/upload/image', formData, options, () => {
    const file = formData.get('file')
    const fileName = file ? file.name : 'image.jpg'
    const fileSize = file ? file.size : 1024
    const fileExtension = fileName.split('.').pop().toLowerCase()
    
    // 图片类型检查
    const allowedImageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp']
    if (!allowedImageTypes.includes(fileExtension)) {
      return mockError('只支持JPG、PNG、GIF、WebP格式的图片', 400)
    }
    
    // 图片大小检查（5MB）
    if (fileSize > 5 * 1024 * 1024) {
      return mockError('图片大小不能超过5MB', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      filename: `${Date.now()}_${fileName}`,
      originalName: fileName,
      size: fileSize,
      extension: fileExtension,
      mimeType: file ? file.type : 'image/jpeg',
      url: `/uploads/images/${Date.now()}_${fileName}`,
      thumbnailUrl: `/uploads/images/thumb_${Date.now()}_${fileName}`,
      width: Math.floor(Math.random() * 1000) + 500,
      height: Math.floor(Math.random() * 1000) + 500,
      uploadTime: new Date().toISOString(),
      hash: `md5_${Date.now()}`,
      category: 'image'
    }, '图片上传成功')
  })
}

/**
 * 上传头像
 * @param {FormData} formData - 头像数据
 * @returns {Promise} 上传结果
 */
export const uploadAvatar = (formData) => {
  return request.upload('/upload/avatar', formData, {}, () => {
    const file = formData.get('file')
    const fileName = file ? file.name : 'avatar.jpg'
    const fileSize = file ? file.size : 1024
    const fileExtension = fileName.split('.').pop().toLowerCase()
    
    // 头像类型检查
    const allowedAvatarTypes = ['jpg', 'jpeg', 'png']
    if (!allowedAvatarTypes.includes(fileExtension)) {
      return mockError('头像只支持JPG、PNG格式', 400)
    }
    
    // 头像大小检查（2MB）
    if (fileSize > 2 * 1024 * 1024) {
      return mockError('头像大小不能超过2MB', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      filename: `avatar_${Date.now()}_${fileName}`,
      originalName: fileName,
      size: fileSize,
      extension: fileExtension,
      mimeType: file ? file.type : 'image/jpeg',
      url: `/uploads/avatars/avatar_${Date.now()}_${fileName}`,
      thumbnailUrl: `/uploads/avatars/thumb_avatar_${Date.now()}_${fileName}`,
      uploadTime: new Date().toISOString(),
      hash: `md5_${Date.now()}`,
      category: 'avatar'
    }, '头像上传成功')
  })
}

/**
 * 上传文档
 * @param {FormData} formData - 文档数据
 * @returns {Promise} 上传结果
 */
export const uploadDocument = (formData) => {
  return request.upload('/upload/document', formData, {}, () => {
    const file = formData.get('file')
    const fileName = file ? file.name : 'document.pdf'
    const fileSize = file ? file.size : 1024
    const fileExtension = fileName.split('.').pop().toLowerCase()
    
    // 文档类型检查
    const allowedDocTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']
    if (!allowedDocTypes.includes(fileExtension)) {
      return mockError('不支持的文档格式', 400)
    }
    
    // 文档大小检查（20MB）
    if (fileSize > 20 * 1024 * 1024) {
      return mockError('文档大小不能超过20MB', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      filename: `doc_${Date.now()}_${fileName}`,
      originalName: fileName,
      size: fileSize,
      extension: fileExtension,
      mimeType: file ? file.type : 'application/pdf',
      url: `/uploads/documents/doc_${Date.now()}_${fileName}`,
      uploadTime: new Date().toISOString(),
      hash: `md5_${Date.now()}`,
      category: 'document',
      pageCount: fileExtension === 'pdf' ? Math.floor(Math.random() * 20) + 1 : null
    }, '文档上传成功')
  })
}

/**
 * 获取文件列表
 * @param {object} params - 查询参数
 * @returns {Promise} 文件列表
 */
export const getFileList = (params = {}) => {
  return request.get('/upload/files', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, category, keyword } = queryParams
    
    const mockFiles = Array.from({ length: 50 }, (_, index) => ({
      id: index + 1,
      filename: `file_${index + 1}.jpg`,
      originalName: `原始文件${index + 1}.jpg`,
      size: Math.floor(Math.random() * 5000000) + 100000,
      extension: ['jpg', 'png', 'pdf', 'doc', 'xls'][Math.floor(Math.random() * 5)],
      mimeType: 'image/jpeg',
      url: `/uploads/file_${index + 1}.jpg`,
      thumbnailUrl: `/uploads/thumb_file_${index + 1}.jpg`,
      uploadTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      hash: `md5_${index + 1}`,
      category: ['image', 'document', 'avatar'][Math.floor(Math.random() * 3)],
      downloadCount: Math.floor(Math.random() * 100),
      uploaderName: `用户${Math.floor(Math.random() * 10) + 1}`
    }))
    
    // 过滤数据
    let filteredFiles = mockFiles
    if (category) {
      filteredFiles = mockFiles.filter(file => file.category === category)
    }
    if (keyword) {
      filteredFiles = filteredFiles.filter(file => 
        file.originalName.includes(keyword) || 
        file.filename.includes(keyword)
      )
    }
    
    // 分页
    const total = filteredFiles.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredFiles.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取文件详情
 * @param {number} id - 文件ID
 * @returns {Promise} 文件详情
 */
export const getFileDetail = (id) => {
  return request.get(`/upload/files/${id}`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      filename: `file_${id}.jpg`,
      originalName: `原始文件${id}.jpg`,
      size: 1024000,
      extension: 'jpg',
      mimeType: 'image/jpeg',
      url: `/uploads/file_${id}.jpg`,
      thumbnailUrl: `/uploads/thumb_file_${id}.jpg`,
      width: 1920,
      height: 1080,
      uploadTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      hash: `md5_${id}`,
      category: 'image',
      downloadCount: Math.floor(Math.random() * 100),
      uploaderName: '当前用户',
      uploaderId: 1,
      description: `这是文件${id}的描述信息`,
      tags: ['标签1', '标签2'],
      metadata: {
        camera: 'iPhone 12',
        location: '北京市朝阳区',
        software: 'Photoshop 2024'
      }
    })
  })
}

/**
 * 删除文件
 * @param {number} id - 文件ID
 * @returns {Promise} 删除结果
 */
export const deleteFile = (id) => {
  return request.delete(`/upload/files/${id}`, {}, () => {
    return mockSuccess(null, '文件删除成功')
  })
}

/**
 * 批量删除文件
 * @param {Array} ids - 文件ID数组
 * @returns {Promise} 删除结果
 */
export const batchDeleteFiles = (ids) => {
  return request.delete('/upload/files/batch', { ids }, () => {
    return mockSuccess(null, `成功删除${ids.length}个文件`)
  })
}

/**
 * 下载文件
 * @param {number} id - 文件ID
 * @returns {Promise} 下载结果
 */
export const downloadFile = (id) => {
  return request.get(`/upload/files/${id}/download`, {}, { responseType: 'blob' }, () => {
    return mockSuccess({
      url: `/uploads/file_${id}.jpg`,
      filename: `原始文件${id}.jpg`
    })
  })
}

/**
 * 获取上传配置
 * @returns {Promise} 上传配置
 */
export const getUploadConfig = () => {
  return request.get('/upload/config', {}, {}, () => {
    return mockSuccess({
      maxFileSize: 10 * 1024 * 1024, // 10MB
      maxImageSize: 5 * 1024 * 1024, // 5MB
      maxDocumentSize: 20 * 1024 * 1024, // 20MB
      maxAvatarSize: 2 * 1024 * 1024, // 2MB
      allowedImageTypes: ['jpg', 'jpeg', 'png', 'gif', 'webp'],
      allowedDocumentTypes: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'],
      allowedFileTypes: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'rar'],
      uploadPath: '/uploads/',
      thumbnailPath: '/uploads/thumbnails/',
      chunkSize: 1024 * 1024, // 1MB
      maxChunks: 100,
      enableChunkUpload: true,
      enableImageCompress: true,
      imageQuality: 0.8,
      thumbnailSize: { width: 200, height: 200 }
    })
  })
}

/**
 * 获取上传统计
 * @param {object} params - 查询参数
 * @returns {Promise} 统计数据
 */
export const getUploadStats = (params = {}) => {
  return request.get('/upload/stats', params, {}, () => {
    return mockSuccess({
      totalFiles: 1250,
      totalSize: 15680000000, // 字节
      totalDownloads: 5680,
      todayUploads: 45,
      todaySize: 156800000,
      categoryStats: [
        { category: 'image', count: 680, size: 8500000000, percentage: 54.4 },
        { category: 'document', count: 420, size: 6200000000, percentage: 33.6 },
        { category: 'avatar', count: 150, size: 980000000, percentage: 12.0 }
      ],
      monthlyStats: Array.from({ length: 12 }, (_, index) => ({
        month: index + 1,
        uploads: Math.floor(Math.random() * 200) + 50,
        size: Math.floor(Math.random() * 2000000000) + 500000000,
        downloads: Math.floor(Math.random() * 500) + 100
      })),
      topFiles: Array.from({ length: 10 }, (_, index) => ({
        id: index + 1,
        filename: `热门文件${index + 1}.jpg`,
        downloadCount: Math.floor(Math.random() * 500) + 100,
        size: Math.floor(Math.random() * 5000000) + 1000000,
        uploadTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
      }))
    })
  })
}

/**
 * 根据文件扩展名获取文件分类
 * @param {string} extension - 文件扩展名
 * @returns {string} 文件分类
 */
function getFileCategory(extension) {
  const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg']
  const documentTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']
  const videoTypes = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv']
  const audioTypes = ['mp3', 'wav', 'flac', 'aac', 'ogg']
  const archiveTypes = ['zip', 'rar', '7z', 'tar', 'gz']
  
  if (imageTypes.includes(extension)) return 'image'
  if (documentTypes.includes(extension)) return 'document'
  if (videoTypes.includes(extension)) return 'video'
  if (audioTypes.includes(extension)) return 'audio'
  if (archiveTypes.includes(extension)) return 'archive'
  
  return 'other'
}